<?php
class M_qin_tree
{
  private $db;
  public function __construct()
  {
    $this->db = M_qin_relation::getInstance();
  }

  public function getFamilyTree($userid, $gender)
  {
    M_Tools::log(__FUNCTION__);
    if (!$userid || !($gender==MALE || $gender==FEMALE))
      return null;

    $top = array($userid);
    $fathers = array();
    /* find the family members in previous and next generation */
    /* 1, get the father of himself */
    $f1 = $this->db->where(array("user_id = $userid", "rel_type = '".FATHER."'"))->fetchOne();
    /* father not found */
    if ($f1['rel_id'])
      {
	$fathers[] = $f1["rel_id"];
	M_Tools::log("get father: ".$f1["rel_id"]);
      }

    /* 2, get the mates */
    $user_field = $gender == MALE ? "user_id" : "rel_id";
    $get_feild = $gender == MALE ? "rel_id" : "user_id";
    $res = $this->db->where(array("$user_field = $userid", "rel_type = '".WIFE."'"))->fetchAll();
    if ($res)
      {
	$mates = M_Tools::convert_mysql_results_to_array($res, $get_feild, $userid);
	$mates = array_keys($mates);
	$top = array_merge($top, $mates);
	M_Tools::log(implode(", ", $mates));

	/* get the first mate's father (father in law) */
	$first_mate = $mates[0];
	$f2 = $this->db->where(array("user_id = $first_mate", "rel_type = '".FATHER."'"))->fetchOne();
	/* father not found */
	if ($f2['rel_id'])
	  {
	    $fathers[] = $f2["rel_id"];
	    M_Tools::log("get father: ".$f2["rel_id"]);
	  }
      }

    /* no fathers */
    if ($fathers)
      $top = $fathers;
    $members = $top;
    /* 3, get fathers' (his father and father in law) children */
    $res = $this->db->setField("user_id")
      ->where(array("rel_id in (".implode(',',$top).")", "rel_type = '".FATHER."'"))->fetchAll();
    /* print_r($res); */
    if ($res)
      {
	$children = M_Tools::convert_mysql_results_to_array($res, "user_id");
	/* print "children: "; */
	/* print_r($children); */
	$children = array_keys($children);
	$members = array_merge($top, $children);
	print "<br/>";
	print_r($children);
	print "<br/>";
	      
	    
	/* 4, get all the grand-children and the mates */
	$res = $this->db->setField(array("user_id", "rel_id", "rel_type"))
	  ->where(array("rel_id in (".implode(',',$members).") or user_id in (".implode(',',$members).")"))->fetchAll();
	if ($res)
	  {
	    /* print_r($res); */
	    /* M_Tools::log(); */
	    $users = M_Tools::convert_mysql_results_to_array($res, "user_id");
	    $rels = M_Tools::convert_mysql_results_to_array($res, "rel_id");
	    $members = array_merge(array_keys($users), array_keys($rels));
	    print_r($users);
	    /* print "<br/>"; */
	    /* print_r($rels); */
	  }
      }

    print_r($members);
    /* 5, get all members' information */
    $this->db->setTable("users");
    $res = $this->db->setField(array("id", "name", "figureurl"))->where("id in (".implode(',', $members).")")->fetchAll();
    $members_info = M_Tools::convert_mysql_results_to_array($res, "id");
    print_r($members_info);

    /* get the tree */
    $tree = aray();
    foreach($fathers as $father)
      {
	if (!isset($tree[$father]))
	  $tree[$father] = array();
	$tree[$father] = getUserTree($father, $users, $members_info);
      }

    return json_encode($tree);
  }

  /* 
   * $userid:  user id you want to handle
   * $relations, relations resultes from relatinos table;
   * $members_info, user info from users table;
   */
  public function getUserTree($userid, $relations, $members_info)
  {
    $res = array();
    $res["id"] = $userid;
    $res["name"] = $members_info[$userid]["name"];
    $res["figureurl"] = $members_info[$userid]["figureurl"];
    foreach($relations as $user)
      {
	if ($user['user_id'] == $userid && $user["rel_type"] == WIFE)
	  {
	    if (!isset($res["mates"]))
	      $res["mates"] = array();
	    $res["mates"][$user['rel_id']] = $members_info[$user['rel_id']];
	  }
	else if ($user['rel_id'] == $userid && $user['rel_type'] == FATHER)
	  {
	    if (!isset($res["children"]))
	      $res["children"] = array();
		
	    $res["children"][$user['user_id']] = getUserTree($user['user_id'], $relations, $members_info);
	  }
      }

    /* get all children's mom, she is also my wife */
    foreach($relations as $user)
      {
	if (array_key_exists($user["user_id"], $res["children"]) && $user["rel_type"] == MOTHER)
	  {
	    if (!isset($res["mates"]))
	      $res["mates"] = array();
	    $res["mates"][$user['rel_id']] = $members_info[$user['rel_id']];
	  }
      }
    return $res;
  }
};
